#!/usr/bin/env python2

from __future__ import with_statement
import sys
import urllib
import itertools
from io import open
from itertools import izip

def second(x):
    return x[1]

def main():
    try:
        bigrams = {}
        path = sys.argv[1]
        if path.startswith(u'http://'):
            words = urllib.urlopen(path).read().split()
        else:
            with open(sys.argv[1]) as f:
                words = f.read().split()
        for bigram in izip(words, words[1:]):
            if bigram in bigrams:
                bigrams[bigram] += 1
            else:
                bigrams[bigram] = 1
        for pair, freq in itertools.islice(sorted(
            list(bigrams.items()), key=second, reverse=True), 10):
            print u':'.join(pair), u'appears', freq, u'times'
    except IOError, e:
        print unicode(e)
    except IndexError:
        print u'File argument is required!'

if __name__ == u'__main__':
    main()
